import { memo, useState, useEffect } from "react";
import {
  Button,
  message,
  Collapse,
  Cascader,
  Card,
  Pagination,
  Upload,
  Select,
  Skeleton,
  Modal,
  Input,
  Form,
} from "antd";
import classNames from "classnames";
import PictureWrapper from "./style";
import UploadFile from "@/components/upload-file/upload-file";

import {
  DeleteFileService,
  GetCommodityAttributeService,
  UpdateFileInfoService,
  UpdateFileLocationService,
} from "@/service";
import { useDispatch, useSelector } from "react-redux";
import {
  fetchPicturesFileThunk,
  IDispatch,
  IStore,
  ResetImageActions,
} from "@/store";
import { UploadOutlined, ExclamationCircleOutlined } from "@ant-design/icons";
import LazyLoad from "react-lazy-load";
import useDebounce from "@/utils/debounce";
import { array } from "snabbdom";
const { Panel } = Collapse;
const { confirm } = Modal;
interface IProps {
  setImage: (val: string) => void;
  children?: any;
  value?: any;
  max?: number;
}
const SelectPicture = memo((props: IProps) => {
  const store = useSelector((state: IStore) => state.file);
  const userStore = useSelector((state: IStore) => state.user);

  const [messageApi, contextHolder] = message.useMessage();
  // 移动数据的选择
  const [moveData, setMoveData] = useState("");
  // 当前的筛选数据  类型和属性
  const [currentShowTab, setCurrentShowTab] = useState("全部");
  const [currentType, setCurrentType] = useState<string>("jpg");
  // 选中的数据
  const [activeArr, setActiveArr] = useState<any[]>([]);
  // 文件数组
  const dispatch = useDispatch<IDispatch>();

  // 侧边栏数据
  const [asideBar, setAsideBar] = useState<any[]>([]);
  // 分页数据
  const [currentPage, setCurrentPage] = useState(1);
  const [currentPageSize, setCurrentPageSize] = useState(20);
  // 处理移动文件数据
  async function handleMoveFileClick() {
    if (moveData.length == 0) {
      messageApi.error("请选择移动的文件!");
      return;
    }
    const res: any = await UpdateFileLocationService({
      arr: activeArr.map((item) => item.id).toString(),
      attribute: moveData,
    });
    console.log("first res", res);
    if (res.code === 0) {
      messageApi.success(res.msg);
      setActiveArr([]);
      getData();
    } else {
      messageApi.error("文件移动失败！");
    }
  }

  // 处理选中的图片
  function handleImageActive(item: any, index: number) {
    const myItem = activeArr.find((itemy) => itemy == item);
    if (activeArr.length >= props.max!) {
      if (myItem) {
        activeArr.splice(
          activeArr.findIndex((itemy) => itemy == item),
          1
        );
        setActiveArr([...activeArr]);
        return;
      }
      message.error("已达到最大个数");
      return;
    }
    if (!myItem) {
      setActiveArr([...activeArr, item]);
      console.log(activeArr);
    } else {
      activeArr.splice(
        activeArr.findIndex((itemy) => itemy == item),
        1
      );
      setActiveArr([...activeArr]);
    }
  }

  // 删除文件
  function handlerDeleteFile() {
    if (!activeArr.length) {
      return messageApi.error("请选择需要删除的文件!!");
    }
    confirm({
      icon: <ExclamationCircleOutlined />,
      content: <h1>是否删除选中文件</h1>,
      onOk() {
        const uuid = activeArr
          .map((item) => item.uuid)
          .reduce((pre, next) => {
            if (!pre || (pre as string).includes(next)) {
              return next;
            }
            return `${pre},${next}`;
          }, "");
        DeleteFileService({
          id: activeArr.map((item) => item.id).join(","),
          uuid,
        }).then((res: any) => {
          if (res.code != 0) {
            messageApi.error(res.msg);
            return;
          }
          setActiveArr([]);
          getData();
          messageApi.success(res.msg);
        });
      },
      onCancel() {
        messageApi.info("文件删除已取消");
      },
    });
  }
  // 获取数据
  function getData() {
    dispatch(ResetImageActions());
    const obj = {
      limit: currentPageSize,
      attribute: currentShowTab == "全部" ? "全部" : currentShowTab,
      type: currentType,
      offset: (currentPage - 1) * currentPageSize,
      page: currentPage,
    };
    dispatch(fetchPicturesFileThunk(obj));
  }
  async function uploadFiles(info: any) {
    if (info.file.status === "done") {
      let res = info.file.response;
      message.destroy();
      if (res.code == 1) {
        message.error(res.msg);
        return;
      }
      getData();
      message.success(res.msg);
    } else if (info.file.status == "uploading") {
      message.loading({ content: "Loading...", duration: 0 });
    } else if (info.file.status === "error") {
      message.destroy();
      message.error(`${info.file.name} 上传出现错误.`);
    }
  }

  const [changeData, setChangeData] = useState<any>({
    isOpen: false,
  });
  function handlerChangeDbClick(item: any) {
    const obj = {
      ...item,
      isOpen: true,
    };
    setChangeData(obj);
    f.setFieldsValue(obj);
  }
  function saveFileClick() {
    UpdateFileInfoService(changeData).then((res: any) => {
      if (res.code == 0) {
        messageApi.success("修改文件成功!");
        getData();
        setChangeData({
          isOpen: false,
        });
        return;
      }
      messageApi.error("修改文件失败!");
    });
  }
  const [f] = Form.useForm();
  useEffect(() => {
    if (asideBar.length == 0) {
      GetCommodityAttributeService({ type: "file" }).then((res) => {
        setAsideBar(res.data);
      });
    }
    getData();
  }, [currentPage, currentPageSize, currentShowTab, currentType]);

  return (
    <PictureWrapper>
      <Card className="w-full">
        {contextHolder}
        <section className="img-header flex justify-between">
          <div className="flex">
            <section className={"flex"}>
              <UploadFile
                getData={() => getData()}
                imageUrl=""
                type={currentType}
                setImageUrl={() => {}}
              >
                <Button type="primary">上传文件</Button>
              </UploadFile>
            </section>
            <section className={"ml-1"}>
              <Cascader
                placeholder="文件移动至"
                options={[
                  {
                    value: "全部",
                    label: "全部",
                  },
                  ...asideBar.map((item) => ({
                    value: item.name,
                    label: item.name,
                    children: item.children?.map((itemy: any) => ({
                      value: itemy.name,
                      label: itemy.name,
                    })),
                  })),
                ]}
                onChange={(val) => setMoveData(val[val.length - 1] as string)}
                changeOnSelect
              />
              <i className="mx-1"></i>
              <Button type={"primary"} onClick={() => handleMoveFileClick()}>
                确定移动
              </Button>
              <i className="mx-1"></i>
              <Button onClick={() => setActiveArr([])}>重置选择</Button>
            </section>
            <section>
              <Upload
                multiple
                action="http://localhost:12345/file/pics"
                name="files"
                headers={{
                  authorization: localStorage.getItem("token") as any,
                }}
                showUploadList={false}
                onChange={(info) => uploadFiles(info)}
              >
                <Button icon={<UploadOutlined />}>上传多个图片</Button>
              </Upload>
              <Button type="primary" danger onClick={() => handlerDeleteFile()}>
                删除
              </Button>
            </section>
          </div>
          <div>
            <span>请筛选类型: </span>
            <Select
              popupMatchSelectWidth
              style={{ width: 120 }}
              defaultValue={"jpg"}
              onChange={(val) => {
                setCurrentPage(1);
                setCurrentType(val);
              }}
              options={[
                { value: "jpg", label: "图片" },
                { value: "pdf", label: "PDF图片" },
                { value: "video", label: "视频" },
                {
                  value: "anima",
                  label: "二次元",
                  disabled: userStore.user.id != 1 ? true : false,
                },
              ]}
            />
          </div>
        </section>
        <section className="img-section">
          <div className="input">
            <div className={"select py-3 my-2 border-b-2 border-pink "}>
              选择的是： <strong>{currentShowTab}</strong>
            </div>
            <div
              className={"bg-gray-100 p-3  border-gray-100"}
              onClick={() => setCurrentShowTab("全部")}
            >
              全部
            </div>
            {asideBar.length <= 0 && (
              <>
                <Skeleton.Button className="h-12 w-full mt-3" block />
                <Skeleton.Button className="h-12 w-full mt-3" block />
                <Skeleton.Button className="h-12 w-full mt-3" block />
                <Skeleton.Button className="h-12 w-full mt-3" block />
                <Skeleton.Button className="h-12 w-full mt-3" block />
                <Skeleton.Button className="h-12 w-full mt-3" block />
              </>
            )}
            {asideBar.map((item, index) => {
              return (
                <Collapse
                  key={index}
                  style={{ marginTop: "20px" }}
                  onChange={(val) => setCurrentShowTab(val[0] ?? "全部")}
                >
                  <Panel header={item.name} key={item.name}>
                    {item.children?.map((itemy: any) => {
                      return (
                        <div
                          key={itemy.name}
                          onClick={() => setCurrentShowTab(itemy.name)}
                          className={"input-item mt-0"}
                        >
                          {itemy.name}
                        </div>
                      );
                    })}
                  </Panel>
                </Collapse>
              );
            })}
          </div>
          <div className="img__container">
            {store.images.length <= 0 && (
              <>
                {Array.from(new Array(15).keys()).map(() => (
                  <Skeleton.Button className="h-56 w-1/6 mr-1 mt-3" block />
                ))}
              </>
            )}
            {store.images.map((item, index) => {
              return (
                <div
                  key={item.id}
                  className={classNames([
                    "show-img",
                    "w-1/6",
                    "h-56",
                    "mt-3",
                    "mr-1",
                    "relative",
                    activeArr.indexOf(item) !== -1 ? "active" : "",
                  ])}
                  onClick={() => handleImageActive(item, index)}
                  onDoubleClick={() => handlerChangeDbClick(item)}
                >
                  {currentType != "video" ? (
                    index < 20 ? (
                      <div>
                        <img
                          className="h-full mx-auto "
                          src={item.url}
                          alt={item.file_name}
                        />
                      </div>
                    ) : (
                      <LazyLoad className="relative text-center">
                        <img
                          className="h-full mx-auto"
                          src={item.url}
                          alt={item.file_name}
                        />
                      </LazyLoad>
                    )
                  ) : (
                    <video controls src={item.url}></video>
                  )}
                  <div className="absolute  left-0 right-0 -bottom-2 bg-white h-10 my-o-text-1">
                    {item.file_name}
                  </div>
                  {activeArr.indexOf(item) != -1 && (
                    <span>{activeArr.indexOf(item)}</span>
                  )}
                </div>
              );
            })}
            <i className="w-1/6"></i>
            <i className="w-1/6"></i>
            <i className="w-1/6"></i>
          </div>
        </section>
        <Pagination
          className={"mt-10 float-right"}
          total={store.total}
          showSizeChanger
          showQuickJumper
          current={currentPage}
          pageSize={currentPageSize}
          onChange={(page, pageSize) => {
            if (page) {
              setCurrentPage(page);
            } else {
              setCurrentPageSize(pageSize);
            }
          }}
          onShowSizeChange={(current, size) => {
            setCurrentPageSize(size);
            setCurrentPage(1);
          }}
          pageSizeOptions={[20, 40, 60, 80, 100]}
          showTotal={(total) => `共 ${total} 个`}
        />
        <Modal
          title="修改文件信息"
          className="file-modal"
          open={changeData.isOpen}
          onOk={() => f.submit()}
          onCancel={() =>
            setChangeData({
              ...changeData,
              isOpen: false,
            })
          }
        >
          <Form
            form={f}
            onFinish={() => saveFileClick()}
            onFinishFailed={() => messageApi.error("请填写信息再提交")}
          >
            <Form.Item
              rules={[{ required: true, message: "名字是必须的" }]}
              label="文件名字"
              name="file_name"
            >
              <Input
                value={changeData.file_name}
                onBlur={(val) =>
                  setChangeData({
                    ...changeData,
                    file_name: val.target.value,
                  })
                }
                placeholder="请输入文件的名称"
              ></Input>
            </Form.Item>
            <Form.Item
              name="desc"
              rules={[{ required: true, message: "描述是必须的" }]}
              label="文件描述"
            >
              <Input.TextArea
                value={changeData.desc}
                onBlur={(val) =>
                  setChangeData({
                    ...changeData,
                    desc: val.target.value,
                  })
                }
                placeholder="请输入文件的描述"
              ></Input.TextArea>
            </Form.Item>
          </Form>
        </Modal>
      </Card>
    </PictureWrapper>
  );
});

export default SelectPicture;
